<?php
/**
 * Created by YuanPan.
 * User: YuanPan
 * Date: 2018/5/12
 * Time: 19:20
 */

namespace app\api\service;


use app\api\lib\exception\MissException;
use app\api\model\User;

class UserToken extends TokenService
{
    protected $AppID;
    protected $AppSecret;
    protected $login_url;
    protected $code;

    public function __construct($code)
    {
        $wxconfig = getWxCache();
        $this->code = $code;
        $this->AppID = $wxconfig['appid'];
        $this->AppSecret = $wxconfig['appsecret'];
        $this->login_url = sprintf(config('weixin.login_url'),$this->AppID,$this->AppSecret,$this->code);
    }

    public function get()
    {
        //code 换取 session_key
        $result = curl_get($this->login_url);
        $wxResult = json_decode($result,true);
        //如果获取数据失败
        if(!$wxResult){
            //框架自带异常处理
            throw new MissException(['msg'=>'提取session_key和openid异常，微信内部错误']);
        }else{
            //返回有数据，判断是否是错误代码
            $final = array_key_exists('errcode',$wxResult);
            if($final){
                //抛出异常，异常内容为微信返回代码和信息
                throw new MissException(['msg'=>$wxResult['errmsg'].',errcode:'.$wxResult['errcode']]);
            }else{
                return $this->grantToken($wxResult);
            }
        }
    }

    private function grantToken($wxResult)
    {
        //拿到openid
        $openid = $wxResult['openid'];
        //判断openid是否存在数据库
        $user = User::get(['openid'=>$openid]);
        if($user){
            //存在则取出用户id
            $uid = $user->id;
        }else{
            //不存在则添加操作
            $uid = $this->newUser($openid);
        }
        //封装微信结果openid,session_key和用户并写入缓存
        $token = $this->saveToCache($wxResult,$uid);
        //返回自定义随机加密的key值
        return $token;
    }

    private function saveToCache($wxResult,$uid)
    {
        //获取加密字符串
        $key = self::generateToken();
        ////将微信返回的正确结果和数据库的uid封装一起
        $wxResult['uid'] = $uid;
        $value = json_encode($wxResult);
        //写入缓存
        $request = cache($key,$value,7200);
        if(!$request){
            throw new MissException([
                'msg'=> '服务器缓存异常',
            ]);
        }
        return $key;
    }

    //新增用户
    public function newUser($openid)
    {
        $user = User::create([
            'openid'=>$openid
        ]);
        return $user->id;
    }
}